<?php

namespace Spider\Weibo\Utils;

use Redis;
use Spider\Weibo\Config\Config;

class RedisClient
{
    private static $instance = null;
    private $redis;

    private function __construct($config = [])
    {
        if (!$config) {
            $config = Config::getInstance()->getRedis();
        }
        $this->redis = new \Redis();
        try {
            $host = $config['host'] ?? '127.0.0.1';
            $port = $config['port'] ?? 6379;
            $db = $config['db'] ?? 0;
            if (!$this->redis->connect($host, $port)) {
                throw new \Exception("Could not connect to Redis server");
            }
            if (isset($config['auth'])) {
                if (!$this->redis->auth($config['auth'])) {
                    throw new \Exception("Redis authentication failed");
                }
            }
            if ($db > 0 && !$this->redis->select($db)) {
                throw new \Exception("Could not select Redis database {$db}");
            }
        } catch (\Exception $e) {
            var_dump("Redis connection failed: " . $e->getMessage());
        }
    }

    public static function getInstance($config = []): self
    {
        if (self::$instance === null) {
            self::$instance = new self($config);
        }
        return self::$instance;
    }

    public function setSubInfo(string $sub, int $expireTime = 7200): bool
    {
        return $this->redis->setex('weibo_sub', $expireTime, $sub);
    }

    public function getSubInfo(): ?string
    {
        $value = $this->redis->get('weibo_sub');
        return $value === false || $value === '' ? null : $value;
    }
    public function deleteSubInfo(): bool
    {
        return $this->redis->del('weibo_sub');
    }
}
